﻿using System.IO;
using System;
using System.Threading;

namespace gcr4csharp
{
    class Program
    {
        static void WriteLog(GCR.LogLevel level, string text)
        {
            DateTime now = DateTime.Now;
            Console.WriteLine("{0} {1}:{2} [{3}]: {4}", now.ToShortDateString(), now.ToShortTimeString(), now.Second, GCR.LogLevelText[(int)level], text);
        }

        static volatile bool quit = false;
        static void ControlThread()
        {
            while (true)
            {
                int flag = Console.Read();
                switch (flag)
                {
                case 'c':
                    GCR.Cancel();
                    break;
                case 'r':
                    if (!GCR.Retry())
                    {
                        Console.WriteLine("No longer to try again");
                    }
                    break;
                case 'q':
                    GCR.Clear();
                    quit = true;
                    break;
                }

            }
        }

        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: gcr4charp host");
                return;
            }

            Thread childThread = new Thread(new ThreadStart(ControlThread));
            childThread.Start();

            GCR.Init(args[0], WriteLog);

            GCR.User = "{\"account\":\"test_account\",\"roleid\":\"sdf23sdfsg345sf2\",\"rolename\":\"test_name\",\"gid\":\"tgame\",\"sid\":124,\"vip\":12}";
            GCR.Text = "I'am a test message!";

            byte[] content = File.ReadAllBytes("t1.cmake");
            GCR.AddFileContent("t1.cmake", content);
            GCR.AddFile("t2.PNG");
            GCR.AddFile("t3.zip");

            bool ok = GCR.Commit((bool ok, int code) =>
            {
                if (ok)
                {
                    Console.WriteLine("Commit completed");
                }
                else
                {
                    Console.WriteLine("Commit failed, code {0}", code);
                    if (GCR.CanRetry)
                    {
                        Console.WriteLine("You can call retry ...");
                    }
                }
            }, 
            (int off, int total) =>
            {
                Console.WriteLine("progress: {0}/{1}, {2}", off, total, ((double)off * 100 / total));
            });
            if (!ok) {
                Console.WriteLine("Commit failed! check logs for details");
            }

            while (!quit)
            {
                GCR.Update();
                Thread.Sleep(10);
            }

            GCR.UnInit();
        }
    }
}
